<?php

require_once 'lib/MagicObject.php';
require_once 'lib/mvc.php';

class Request extends ArrayObject implements IControllerRequest {
	function __construct () {
		$this->offsetSet('action', 'list_bookmarklets');
		
		if (isset($_SERVER['argv'][0])) {
			$this->offsetSet('action', 'get_bookmark');
			$this->offsetSet('bookmarklet_name', $_SERVER['argv'][0]);
		}
	}
	function getAction () {
		return $this->offsetGet('action');
	}
	function getParams () {
		return $this;
	}
	function getController() {
		return new MainController($this);
	}
}

class Bookmarklet extends MagicObject {
	function __construct ($directory, $manifest) {
		parent::__construct();
		$this->manifest = $manifest;
		$this->directory = $directory;
	}
	function getJs() {
		$res = array();
		foreach ($this->manifest['js'] as $js) {
			$res[] = $this->directory. "/$js";
		}
		return $res;
	}
	function getName () {
		return $this->manifest['name'];
	}
	function getId() {
		return basename($this->directory);
	}
}

class BookmarkletsIterator extends DirectoryIterator {
	static private $BOOKMARKLETS_DIR = './bookmarklets';
	
	function __construct () {
		parent::__construct(self::$BOOKMARKLETS_DIR);
	}
	
	function current () {
		$res = parent::current();
		assert(!$res->isDot());
		
		$manifest = file_get_contents(self::$BOOKMARKLETS_DIR. '/'. $res->getFilename(). '/manifest.json');
		$manifest_array = json_decode($manifest, true);
		
		return new Bookmarklet(self::$BOOKMARKLETS_DIR. '/'. $res->getFilename(), $manifest_array);
	}
	
	function next () {
		$next = parent::next();
		if (parent::current()->isDot()) {
			return $this->next();
		}
		return $next;
	}

	public function rewind() {
		parent::rewind();
		if (parent::current()->isDot()) {
			$this->next();
		}
		
		// skip .svn
		if (!file_exists(self::$BOOKMARKLETS_DIR. '/'. parent::current()->getFilename(). '/manifest.json')) {
			$this->next();
		}
	}
}

class MainController extends Controller {
	function initialize () {
		$this->bookmarklet_dirs = new BookmarkletsIterator();
	}
	function list_bookmarklets () {
		$this->url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
	}
	function get_bookmark () {
		// search bookmark by iterating over directories
		foreach ($this->bookmarklet_dirs as $b) {
			if ($b->getId() == $this->params['bookmarklet_name']) {
				foreach ($b->js as $js) {
					echo "\n//$js\n";
					echo file_get_contents($js);
				}
			}
		}
		$this->view = false;
	}
}

$request = new Request();
Dispatcher::dispatch($request);

?>